<?php

namespace App\Listeners\Refund;

use App\Events\Refund;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Services\PosApi\BalanceRefund;

class Balance
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param Refund $event
     * @return void
     */
    public function handle(Refund $event)
    {
        $info = $event->info;

        if ($info['refund_amount'] > 0) {
            if($info['balance_amount']>0){
                $mcService = new BalanceRefund();
                foreach ($info['items'] as $item) {
                    if ($item['pay_platform'] == $mcService->paymentCode) {
                        $money = min($info['refund_amount'],$item['pay_amount']);
                        $result = $mcService->handle($info,$item,$money);
                        if ($result['status'] === 1) {
                            $event->info['refund_amount'] -= $money;
                        }
                    }
                }
            }

        } else {
            return false;
        }
    }
}
